package com.ruix.app.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;

//import com.danikula.videocache.CacheListener;
//import com.danikula.videocache.HttpProxyCacheServer;
import com.ruix.app.RuiApplication;
import com.ruix.app.manager.MediaPlayerManager;
import com.ruix.app.receiver.NoisyAudioStreamReceiver;
import com.ruix.app.util.LogUitl;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by hadexs on 2017/5/23.
 */

public class MusicService extends Service {


    private Context mContext;
//    private MediaPlayerLisenter onCacheListener;

    private IntentFilter mNoisyFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    private NoisyAudioStreamReceiver mNoisyReceiver = new NoisyAudioStreamReceiver();
//    private   HttpProxyCacheServer proxy;
    private ArrayList<MusicPlayerLisenter> playerLisenters;
    private boolean isPausing;
    private boolean isPreparing;
    private CountDownTimer countDownTimer;

    public static MediaPlayer mediaPlayer; //= new MediaPlayer();

    @Override
    public void onCreate() {
        super.onCreate();
        initMediaPlayer();
    }


    public static void startCommand(Context context, String action) {
        Intent intent = new Intent(context, PlayService.class);
        intent.setAction(action);
        context.startService(intent);
    }


    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case "ACTION_MEDIA_PLAY_PAUSE":
                    playPause();
                    break;
                case "ACTION_MEDIA_PAUSE":
                    pause();
                    break;
            }
        }
        return START_STICKY;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    private void initMediaPlayer(){
//        proxy = RuiApplication.getProxy(RuiApplication.getAppContext());
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(MediaPlayer mp) {
                if (playerLisenters != null){
                    for (MusicPlayerLisenter lisenter:playerLisenters) {
                        if (lisenter != null){
                            lisenter.onSeekComplete(mp);
                        }
                    }
                }

            }
        });


        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                if (playerLisenters != null){
                    for (MusicPlayerLisenter lisenter:playerLisenters) {
                        if (lisenter != null){
                            lisenter.onBufferingUpdate(mp,percent);
                        }
                    }
                }
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (playerLisenters != null){
                    for (MusicPlayerLisenter lisenter:playerLisenters) {
                        if (lisenter != null){
                            lisenter.onPrepared(mp);
                        }
                    }
                }
                isPreparing = false;
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (playerLisenters != null){
                    for (MusicPlayerLisenter lisenter:playerLisenters) {
                        if (lisenter != null){
                            lisenter.onCompletion(mp);
                        }
                    }
                }
            }
        });

        try {
//            checkCachedState();
//            proxy.registerCacheListener(this, url);
//            String proxyUrl = proxy.getProxyUrl(url);
//            mediaPlayer.setDataSource(proxyUrl);
//            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void prepareUrl(String videoUrl){
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepareAsync();//prepare之后自动播放
            isPreparing = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public void playUrl(String videoUrl)
//    {
//        try {
////            checkCachedState(videoUrl);
//            proxy.registerCacheListener(this, videoUrl);
//            String proxyUrl = proxy.getProxyUrl(videoUrl);
//            mediaPlayer.reset();
//            mediaPlayer.setDataSource(proxyUrl);
//            mediaPlayer.prepare();
////
////            mediaPlayer.setDataSource(RuiApplication.getAppContext(), Uri.parse(videoUrl));
////            mediaPlayer.prepare();//prepare之后自动播放
////            mediaPlayer.start();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    public void playPause() {
        if (isPreparing()) {
            return;
        }
        if (isPlaying()) {
            pause();
        } else {
            start();
        }
    }

    public void start(){
        if (mediaPlayer != null) {
            try {
                if (!isPreparing()){
                    mediaPlayer.start();
                    isPausing = false;
                    registerReceiver(mNoisyReceiver, mNoisyFilter);
                    startTimer();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public void pause() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.pause();
                isPausing = true;
                unregisterReceiver(mNoisyReceiver);
                stopTimer();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public void seekTo(int msec){
        if (mediaPlayer != null) {
            try {
                mediaPlayer.seekTo(msec);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public int getDuration(){
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.getDuration();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return  -1;
    }

    public int getCurrentPosition(){
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.getCurrentPosition();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return  -1;
    }

    public boolean isPlaying(){
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.isPlaying();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return false;
    }



    public void release(){
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if (playerLisenters != null){
            playerLisenters.clear();
        }

        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }


    public boolean isPausing() {
        return mediaPlayer != null && isPausing;
    }

    public boolean isPreparing() {
        return mediaPlayer != null && isPreparing;
    }

    public void addLisenter(MusicPlayerLisenter lisenter){
        if (playerLisenters == null){
            playerLisenters = new ArrayList<>();
        }
        playerLisenters.add(lisenter);
    }

    public void removeLisenter(MusicPlayerLisenter lisenter){
        if (playerLisenters != null){
            playerLisenters.remove(lisenter);
        }
    }



    @Override
    public void onDestroy() {
        release();
        super.onDestroy();
    }


    public void buildTimer(){
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(Integer.MAX_VALUE, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (playerLisenters != null) {
                        for (MusicPlayerLisenter lisenter : playerLisenters) {
                            if (lisenter != null) {
                                lisenter.onPlayerTick(getDuration(),getCurrentPosition());
                            }
                        }
                    }
                }

                @Override
                public void onFinish() {
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }
                }
            };
        }
    }

    private void stopTimer(){
        if (countDownTimer != null){
            countDownTimer.cancel();
        }
    }

    private void startTimer(){
        buildTimer();
        if (countDownTimer != null){
            countDownTimer.start();
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBinder();
    }

//    @Override
//    public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
//
//    }

    public class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

}
